﻿using System.Collections.Generic;
using System.Net.Http;
using System.Net.Security;
using System.Text;
using System.Threading.Tasks;

namespace Xlit.Utility
{
    public class HttpContentTypeEnum
    {
        public const string FORM = "multipart/form-data";
        public const string URLCODED = "application/x-www-form-urlencoded";
        public const string JSON = "application/json";
        public const string TEXT = "application/text";
        public const string XML = "application/xml";
    }

    /// <summary>
    ///  Http 请求帮助类
    /// </summary>
    public class HttpUtil
    {
        /// <summary>
        ///  Http 请求默认编码
        /// </summary>
        private static readonly Encoding DefaultEncoding = Encoding.UTF8;
        // 
        private static readonly RemoteCertificateValidationCallback _remoteCertificateValidationCallback =
            new RemoteCertificateValidationCallback((sender, certificate, chain, errors) => errors == SslPolicyErrors.None);

        #region HttpWebResponse

        /// <summary>
        ///  Get
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="encode">编码</param>
        /// <returns></returns>
        //public static string Get(string host, IDictionary<string, object> header, Encoding encode = null)
        //{
        //    try
        //    {
        //        var request = (HttpWebRequest)WebRequest.Create(host);
        //        request.Method = "GET";
        //        request.CookieContainer = new CookieContainer();
        //        if (request == null)
        //        {
        //            var errMsg = $"请求 {host} 为空或者不是一个 Http 请求";
        //            throw new NullReferenceException(errMsg);
        //        }
        //        if (header != null && header.Count > 0)
        //        {
        //            foreach (var head in header)
        //                request.Headers.Add(head.Key, head.Value.ToString());
        //        }
        //        //if (cert != null)
        //        //    request.ClientCertificates.Add(cert);


        //        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        //        using var responseStream = response.GetResponseStream();
        //        var reader = new StreamReader(responseStream, encode ?? DefaultEncoding);
        //        return reader.ReadToEnd();
        //    }
        //    catch (WebException ex)
        //    {
        //        //var response = (ex.Response as HttpWebResponse);
        //        //Logger.Error(ex, $"获取响应失败, {response.StatusCode}");
        //        throw ex;
        //    }
        //    catch (Exception ex)
        //    {
        //        //Logger.Error(ex, $"获取响应失败, 原因:{ex.Message}");
        //        throw ex;
        //    }
        //}

        #endregion

        #region WebClient

        #endregion

        #region HttpClient

        /// <summary>
        ///  Get
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="header"></param>
        /// <returns></returns>
        public static async Task<HttpResponseMessage> GetAsync(string uri, IDictionary<string, string> header = null)
        {
            HttpClient client = new HttpClient();

            if (header != null && header.Count > 0)
            {
                foreach (var head in header)
                    client.DefaultRequestHeaders.TryAddWithoutValidation(head.Key, head.Value.ToString());
            }
            return await client.GetAsync(uri);
        }

        /// <summary>
        ///  Post
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="param"></param>
        /// <param name="header"></param>
        /// <returns></returns>
        public static async Task<HttpResponseMessage> PostAsync(string uri, string param, IDictionary<string, string> header = null)
        {
            HttpClient client = new HttpClient();

            if (header != null && header.Count > 0)
            {
                foreach (var head in header)
                    client.DefaultRequestHeaders.TryAddWithoutValidation(head.Key, head.Value);
            }

            HttpContent content = null;
            if (header != null && header.ContainsKey("Content-Type"))
            {
                switch(header["Content-Type"])
                {
                    case HttpContentTypeEnum.FORM:
                        content = new MultipartFormDataContent(param);
                        break;
                    case HttpContentTypeEnum.URLCODED:
                        var paramDict = new Dictionary<string, string>();
                        var urlencoded = param.Split("&");
                        foreach(var _par in urlencoded)
                        {
                            var keyValue = _par.Split("=");
                            paramDict.Add(keyValue[0], keyValue[1]);
                        }
                        content = new FormUrlEncodedContent(paramDict);
                        break;
                    case HttpContentTypeEnum.JSON:
                    case HttpContentTypeEnum.TEXT:
                    case HttpContentTypeEnum.XML:
                        content = new StringContent(param, Encoding.UTF8, header["Content-Type"]);
                        break;
                    default: break;
                }
            }
            return await client.PostAsync(uri, content);
        }

        /// <summary>
        ///  Post
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="param"></param>
        /// <param name="header"></param>
        /// <returns></returns>
        public static async Task<HttpResponseMessage> PostAsync(string uri, IDictionary<string, string> param, IDictionary<string, string> header = null)
        {
            HttpClient client = new HttpClient();

            if (header != null && header.Count > 0)
            {
                foreach (var head in header)
                    client.DefaultRequestHeaders.TryAddWithoutValidation(head.Key, head.Value);
            }

            HttpContent content = new FormUrlEncodedContent(param);
            return await client.PostAsync(uri, content);
        }

        /// <summary>
        ///  Post
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="param"></param>
        /// <param name="header"></param>
        /// <returns></returns>
        public static async Task<HttpResponseMessage> PostAsync(string uri, byte[] param, IDictionary<string, string> header = null)
        {
            //HttpClient client = new HttpClient();
            //if (header != null && header.Count > 0)
            //{
            //    foreach (var head in header)
            //        client.DefaultRequestHeaders.Add(head.Key, head.Value.ToString());
            //}
            //StreamContent content = new StreamContent(param);
            //var response = await client.PostAsync(uri, content);
            //return await response.Content.ReadAsStringAsync();
            return null;
        }

        #endregion
    }
}
